﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using Vit.Common;
using Vit.Web;
using Vit.Common.Providers;
using Vit.Web.Providers;

namespace Vit.Mvc.Results
{
    public class ErrorResult : ViewResult
    {
        private string message;

        public ErrorResult()
        {
        }

        public ErrorResult(string message)
        {
            this.message = message;
        }

        public override void ExecuteResult(ControllerContext context)
        {
            ViewName = "Error";

            ViewData = context.Controller.ViewData;
            TempData = context.Controller.TempData;

            Exception ex = null;
            if (string.IsNullOrEmpty(message))
                ex = context.HttpContext.Server.GetLastError();
            else
                ex = new Exception(message);
            string controller = context.RouteData.GetRequiredString("controller");
            string action = context.RouteData.GetRequiredString("action");

            try
            {
                WebUnity.Current.LogService.Run(p => { p.Error("Error", ex.Message); return false; });
            }
            catch { }

            HandleErrorInfo error = new HandleErrorInfo(ex, controller, action);

            ViewData.Model = error;

            base.ExecuteResult(context);

            context.HttpContext.Response.StatusDescription = "Internal Error";
            context.HttpContext.Response.StatusCode = 500;
        }
    }
}
